package com.dzl.goods;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzl.asynthread.SyncInitDataServiceImpl;
import com.dzl.base.controller.BaseController;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.constant.OperationConstant;
import com.dzl.constant.WelfareGoodsEnum;
import com.dzl.goods.pojo.WelfareGoods;
import com.dzl.goods.pojo.WelfareGoodsAttr;
import com.dzl.goods.pojo.dto.WelfareGoodsAttrCostPriceDto;
import com.dzl.goods.pojo.dto.WelfareGoodsBatchUpdateDto;
import com.dzl.goods.pojo.dto.WelfareGoodsManageAddDto;
import com.dzl.goods.pojo.query.WelfareGoodsManageQuery;
import com.dzl.goods.pojo.vo.WelfareGoodsDetailVo;
import com.dzl.goods.pojo.vo.WelfareGoodsManageVo;
import com.dzl.goods.pojo.vo.WelfareSkuGoodsVo;
import com.dzl.goods.service.WelfareGoodsAttrService;
import com.dzl.goods.service.WelfareGoodsService;
import com.dzl.operation.service.OperationLogService;
import com.dzl.util.EmptyUtils;
import com.dzl.util.JsonResult;
import com.dzl.util.PageUtils;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品表(WelfareGoods)表控制层
 * @author ChenLong
 * @date 2021-05-26 11:30:42
 */
@Slf4j
@RestController
@RequestMapping("/welfareGoods")
public class WelfareGoodsController extends BaseController {

    @Autowired
    private WelfareGoodsService welfareGoodsService;
    @Autowired
    private WelfareGoodsAttrService welfareGoodsAttrService;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private SyncInitDataServiceImpl syncInitDataServiceImpl;

    /**
     * 商品管理列表查询
     * @param query 查询实体类
     * @return com.dzl.util.PageUtils
     * @author ChenLong
     * @date 2021-05-29 11:56:58
     **/
    @GetMapping("getGoodsListManage")
    public PageUtils<WelfareGoodsManageVo> getGoodsListManage(WelfareGoodsManageQuery query) {
        log.info("getGoodsListManage in: " + query.toString());
        //如果选商品弹窗中，该点击的东西没有选择商品，但是筛选的时候又点了是，就没有数据
        if(EmptyUtils.isEmpty(query.getCheckedIds()) && EmptyUtils.isNotEmpty(query.getIsChecked()) && query.getIsChecked() == 1) {
            List<WelfareGoodsManageVo> goodsManageVoList = new ArrayList<>();
            PageInfo<WelfareGoodsManageVo> pageInfo = new PageInfo<>(goodsManageVoList);
            return new PageUtils<>(pageInfo);
        } else {
            query.setEnterpriseId(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID);
            PageInfo<WelfareGoodsManageVo> pageInfo = welfareGoodsService.getWelfareGoodsListPage(query);
            return new PageUtils<>(pageInfo);
        }
    }

    /**
     * 商品管理批量更新，上架、下架、改分区、改供应商
     * @param dto 商品批量管理实体对象
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @date 2021-05-29 14:57:22
     **/
    @PostMapping("updateGoodsBatchManage")
    public JsonResult<Integer> updateGoodsBatchManage(@RequestBody WelfareGoodsBatchUpdateDto dto) {
        log.info("updateGoodsBatchManage in");
        if (EmptyUtils.isEmpty(dto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        // 商品id不能为空
        if (EmptyUtils.isEmpty(dto.getIds())) {
            return JsonResult.paramErrWithMsg("商品id不能为空");
        }
        if(!dto.getIds().contains("_")){
            return JsonResult.paramErrWithMsg("商品id参数格式不对，请对照接口文档传参");
        }
        dto.setUpdater(getAdminInfo().getId());
        dto.setUpdaterName(getAdminInfo().getUserName());
        dto.setFirstClassifyId(null);
        dto.setSecondClassifyId(null);
        dto.setThirdClassifyId(null);
        dto.setIsShow(null);
        dto.setBrandId(null);
        dto.setPartitionId(null);
        dto.setSupplierId(null);
        Integer count = welfareGoodsService.updateGoodsBatchManage(dto);
        if(count>0){
            String[] ids_ = dto.getIds().split(",");
            for(int i=0;i<ids_.length;i++){
                String[] item = ids_[i].split("_");
                Integer goodsId = Integer.valueOf(item[0]);
                syncInitDataServiceImpl.syncUpdateGoodsStatusToCompany(goodsId,dto.getGoodsStatus());
            }
            return JsonResult.success(count);
        }else{
            return JsonResult.fail();
        }

    }

    /**
     * 商品管理批量更新分类
     * @param dto 商品分类实体
     * @return int
     * @author ChenLong
     * @date 2021-05-29 16:41:21
     **/
    @PostMapping("updateGoodsClassifyBatch")
    public JsonResult<Integer> updateGoodsClassifyBatch(@RequestBody WelfareGoodsBatchUpdateDto dto) {
        log.info("updateGoodsClassifyBatch in");
        // 商品id不能为空
        if (EmptyUtils.isEmpty(dto.getIds())) {
            return JsonResult.paramErrWithMsg("商品id不能为空");
        }
        if(!dto.getIds().contains("_")){
            return JsonResult.paramErrWithMsg("商品id参数格式不对，请对照接口文档传参");
        }
        if (EmptyUtils.isEmpty(dto.getFirstClassifyId())) {
            return JsonResult.paramErrWithMsg("一级分类ID不能为空");
        }
        if (EmptyUtils.isEmpty(dto.getSecondClassifyId())) {
            return JsonResult.paramErrWithMsg("二级分类ID不能为空");
        }
        if (EmptyUtils.isEmpty(dto.getThirdClassifyId())) {
            return JsonResult.paramErrWithMsg("三级分类ID不能为空");
        }
        dto.setUpdater(getAdminInfo().getId());
        dto.setGoodsStatus(null);
        dto.setIsShow(null);
        dto.setBrandId(null);
        dto.setPartitionId(null);
        dto.setSupplierId(null);
        return JsonResult.success(welfareGoodsService.updateGoodsClassifyBatch(dto));
    }

    /**
     * 商品管理批量更新供应商
     * @param dto 商品分类实体
     * @return int
     * @author ChenLong
     * @date 2021-05-29 16:41:21
     **/
    @PostMapping("updateGoodsSupplierBatch")
    public JsonResult<Integer> updateGoodsSupplierBatch(@RequestBody WelfareGoodsBatchUpdateDto dto) {
        log.info("updateGoodsSupplierBatch in");
        // 商品id不能为空
        if (EmptyUtils.isEmpty(dto.getIds())) {
            return JsonResult.paramErrWithMsg("商品id不能为空");
        }
        if(!dto.getIds().contains("_")){
            return JsonResult.paramErrWithMsg("商品id参数格式不对，请对照接口文档传参");
        }
        if (EmptyUtils.isEmpty(dto.getSupplierId())) {
            return JsonResult.paramErrWithMsg("供应商不能为空");
        }
        if (EmptyUtils.isEmpty(dto.getBrandId())) {
            return JsonResult.paramErrWithMsg("品牌不能为空");
        }
        dto.setUpdater(getAdminInfo().getId());
        String[] ids_ = dto.getIds().split(",");
        StringBuffer idsBuf1 = new StringBuffer(); //自有商品
        for(int i=0;i<ids_.length;i++){
            String[] item = ids_[i].split("_");
            Integer goodsId = Integer.valueOf(item[0]);
            Integer platformId = Integer.valueOf(item[1]);
            Integer goodsStatus = Integer.valueOf(item[2]);
            Integer goodsType = Integer.valueOf(item[3]);
            if(goodsType == WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode()){
                throw new CommonException("操作失败，虚拟商品供应商不允许批量修改");
            }
            idsBuf1.append(goodsId).append(",");
        }
        dto.setIds(idsBuf1.substring(0,idsBuf1.length()-1));
        dto.setFirstClassifyId(null);
        dto.setSecondClassifyId(null);
        dto.setThirdClassifyId(null);
        dto.setIsShow(null);
        dto.setPartitionId(null);
        dto.setGoodsStatus(null);
        return JsonResult.success(welfareGoodsService.updateGoodsSupplierBatch(dto));
    }

    /**
     * 商品添加
     * @param welfareGoodsManageAddDto 商品添加dto实体类
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @date 2021-06-02 16:01:36
     **/
    @PostMapping("addGoodsManage")
    public JsonResult<Integer> addGoodsManage(@RequestBody WelfareGoodsManageAddDto welfareGoodsManageAddDto) {
        log.info("addGoodsManage in");
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        welfareGoodsManageAddDto.setEnterpriseId(CommonConstants.DEFAULT_PLATFORM_ENTERPRISE_ID);
        Map<String, Object> resMap = welfareGoodsService.addGoodsManage(welfareGoodsManageAddDto, getAdminInfo());
        if (resMap.get("code").equals(1)) {
            Object goodsId = resMap.get("goodsId");
            if(goodsId!=null){
                syncInitDataServiceImpl.syncAddGoodsToCompany(Integer.valueOf(resMap.get("goodsId").toString()));
            }
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 批量修改一个商品的多个规格的成本价
     * @date 2021/10/12 14:17
     * @author caobucao
     * @param jsonArray 修改的列表
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @PostMapping("/updateGoodsAttrCostPrice")
    public JsonResult<Integer> updateGoodsAttrCostPrice(@RequestBody JSONArray jsonArray) {
        if(EmptyUtils.isEmpty(jsonArray)) {
            return JsonResult.paramErrWithMsg("前端传入数据为空！");
        }
        List<WelfareGoodsAttrCostPriceDto> list = jsonArray.toJavaList(WelfareGoodsAttrCostPriceDto.class);
        return JsonResult.success(welfareGoodsService.updateGoodsAttrCostPrice(list));
    }

    /**
     * 商品及规格修改
     * @param welfareGoodsManageAddDto 商品修改dto实体类
     * @return com.dzl.util.JsonResult<java.lang.Object>
     * @author ChenLong
     * @date 2021-06-02 16:01:56
     **/
    @PostMapping("updateGoodsManage")
    public JsonResult<Integer> updateGoodsManage(@RequestBody WelfareGoodsManageAddDto welfareGoodsManageAddDto) {
        log.info("updateGoodsManage in");
        if (EmptyUtils.isEmpty(welfareGoodsManageAddDto)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        welfareGoodsManageAddDto.setUpdater(getAdminInfo().getId());
        welfareGoodsManageAddDto.setUpdaterName(getAdminInfo().getUserName());
        Map<String, Object> resMap = welfareGoodsService.updateGoodsManage(welfareGoodsManageAddDto);
        if (resMap.get("code").equals(1)) {
            Object goodsId = resMap.get("goodsId");
            if(goodsId!=null){
                syncInitDataServiceImpl.syncUpdateGoodsToCompany(Integer.valueOf(resMap.get("goodsId").toString()));
            }
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 获取商品详细信息
     * @param goodsId 商品id
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-18 20:47:38
     **/
    @GetMapping(value = "getGoodsInfo")
    public JsonResult<WelfareGoodsDetailVo> getGoodsInfo(Integer goodsId) {
        log.info("getGoodsInfo in goodsId: " + goodsId);
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(welfareGoodsService.getGoodsInfoDetail(goodsId));
    }

    /**
     * 获取商品规格列表
     * @param goodsId 商品id
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-18 19:43:07
     **/
    @GetMapping(value = "getWelfareGoodsAttr")
    public JsonResult<List<WelfareGoodsAttr>> getWelfareGoodsAttr(Integer goodsId) {
        log.info("getWelfareGoodsAttr in goodsId: " + goodsId);
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(welfareGoodsService.getWelfareGoodsAttr(goodsId));
    }

    /**
     * 获取商品规格列表
     * @param goodsId 商品id
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-18 19:43:07
     **/
    @GetMapping(value = "getWelfareGoodsAttrNoCutLockQuantity")
    public JsonResult<List<WelfareGoodsAttr>> getWelfareGoodsAttrNoCutLockQuantity(Integer goodsId) {
        log.info("getWelfareGoodsAttr in goodsId: " + goodsId);
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(welfareGoodsService.getWelfareGoodsAttrNoCutLockQuantity(goodsId));
    }

    /**
     * 获取商品规格列表
     * @param goodsId
     * @return com.dzl.util.JsonResult<java.util.List   <   com.dzl.goods.pojo.vo.WelfareGoodsAttrVo>>
     * @date 2021/8/27 0027 14:00
     * @author wangjian
     */
    @GetMapping(value = "getWelfareGoodsAttrVo")
    public JsonResult<List<WelfareSkuGoodsVo>> getWelfareGoodsAttrVo(Integer goodsId) {
        log.info("getWelfareGoodsAttr in goodsId: " + goodsId);
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("参数错误");
        }
        return JsonResult.success(welfareGoodsService.getWelfareGoodsAttrVo(goodsId));
    }

    /**
     * 上架下架商品
     * @param jsonObject
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     * @date 2021/6/11 15:39
     * @author caobucao
     */
    @PostMapping("downOrUpGoods")
    public JsonResult<Integer> downOrUpGoods(@RequestBody JSONObject jsonObject) {
        Integer goodsId = jsonObject.getInteger("id");
        Integer newGoodsStatus = jsonObject.getInteger("goodsStatus");
        WelfareGoods welfareGoods = new WelfareGoods();
        welfareGoods.setId(goodsId);
        welfareGoods.setUpdateTime(new Date());
        welfareGoods.setGoodsStatus(newGoodsStatus);
        //查询商品
        WelfareGoods oldGoods = welfareGoodsService.selectByPrimaryKey(goodsId);

        if (EmptyUtils.isEmpty(oldGoods.getGoodsName())) {
            return JsonResult.paramErrWithMsg("商品名不能为空");
        }
        /*if (EmptyUtils.isEmpty(oldGoods.getPartitionId())) {
            return JsonResult.paramErrWithMsg("分区不能为空");
        }*/
        if (EmptyUtils.isEmpty(oldGoods.getSupplierId())) {
            return JsonResult.paramErrWithMsg("供应商不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getBrandId())) {
            return JsonResult.paramErrWithMsg("品牌不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getGoodsType())) {
            return JsonResult.paramErrWithMsg("商品类型不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getFirstClassifyId())) {
            return JsonResult.paramErrWithMsg("一级分类不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getSecondClassifyId())) {
            return JsonResult.paramErrWithMsg("二级分类不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getThirdClassifyId())) {
            return JsonResult.paramErrWithMsg("三级分类不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getGoodsImg())) {
            return JsonResult.paramErrWithMsg("商品图片不能为空");
        }
        if (EmptyUtils.isEmpty(oldGoods.getGoodsDetail().trim())) {
            return JsonResult.paramErrWithMsg("商品详情不能为空");
        }
        //获取商品SKU
        Example example = new Example(WelfareGoodsAttr.class);
        example.createCriteria().andEqualTo("goodsId", oldGoods.getId());
        List<WelfareGoodsAttr> attrList = welfareGoodsAttrService.selectByExample(example);
        if (CollectionUtils.isEmpty(attrList)) {
            return JsonResult.paramErrWithMsg("商品规格不能为空");
        }
        if (oldGoods.getGoodsType().equals(WelfareGoodsEnum.GOODS_TYPE_VIRTUAL.getCode())) {
            //如果是虚拟商品
            if (EmptyUtils.isEmpty(oldGoods.getBuyLimit())) {
                return JsonResult.paramErrWithMsg("虚拟商品购买限制必填");
            }
        }
        //保存修改日志
        String goodsOldStatus = "上架";
        if(oldGoods.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){
            goodsOldStatus = "下架";
        }else if(oldGoods.getGoodsStatus()==WelfareGoodsEnum.GOODS_STATUS_TYPE_DRAFT.getCode()){
            goodsOldStatus = "草稿";
        }
        if(newGoodsStatus == WelfareGoodsEnum.GOODS_STATUS_TYPE_SHELVES.getCode()){//上架
            operationLogService.saveOperationLog(welfareGoods.getId(),"修改商品["+oldGoods.getGoodsName()+"]状态由"+goodsOldStatus+"变成上架", OperationConstant.TypeEnum.GOODS_UPDATE_STATUS_TO_SHELVES.getType(),getAdminInfo().getId(),getAdminInfo().getUserName());
            syncInitDataServiceImpl.syncUpdateGoodsStatusToCompany(goodsId,newGoodsStatus);
        }else if(newGoodsStatus == WelfareGoodsEnum.GOODS_STATUS_TYPE_DOWN.getCode()){//下架
            operationLogService.saveOperationLog(welfareGoods.getId(),"修改商品["+oldGoods.getGoodsName()+"]状态由"+goodsOldStatus+"变成下架",OperationConstant.TypeEnum.GOODS_UPDATE_STATUS_TO_DOWN.getType(),getAdminInfo().getId(),getAdminInfo().getUserName());
            syncInitDataServiceImpl.syncUpdateGoodsStatusToCompany(goodsId,newGoodsStatus);
        }
        return JsonResult.success(welfareGoodsService.updateByPrimaryKeySelective(welfareGoods));
    }

    /**
     * 批量隐藏（不隐藏）商品
     * @param jsonObject 入参
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     * @date 2021/7/14 0014 9:30
     * @author wangjian
     */
    @PostMapping("goodsHide")
    public JsonResult<Integer> goodsHide(@RequestBody JSONObject jsonObject) {
        String goodsIds = jsonObject.getString("goodsIds");
        Integer isShow = jsonObject.getInteger("isShow");
        if (EmptyUtils.isEmpty(goodsIds)) {
            return JsonResult.paramErrWithMsg("请选择商品");
        }
        return JsonResult.success(welfareGoodsService.updateGoodsHide(goodsIds, isShow));
    }

    /**
     * 设置商品是否同步非自营
     * @param jsonObject 入参
     * @date 2022/02/15 09:37
     * @author liuguanjun
     */
    @PostMapping("updateSyncNonSelfSupportStatus")
    public JsonResult<Integer> updateSyncNonSelfSupportStatus(@RequestBody JSONObject jsonObject) {
        Integer goodsId = jsonObject.getInteger("goodsId");
        Integer syncNonSelfSupport = jsonObject.getInteger("syncNonSelfSupport");
        if (EmptyUtils.isEmpty(goodsId)) {
            return JsonResult.paramErrWithMsg("商品id不能传空");
        }
        if (syncNonSelfSupport == null) {
            return JsonResult.paramErrWithMsg("同步状态值不能传空");
        }
        WelfareGoods welfareGoods = new WelfareGoods();
        welfareGoods.setId(goodsId);
        welfareGoods.setSyncNonSelfSupport(syncNonSelfSupport);
        welfareGoodsService.updateByPrimaryKeySelective(welfareGoods);
        //修改企业端导入商品的状态
        welfareGoodsService.updateGoodsSyncNonSelfSupportStatus(goodsId, syncNonSelfSupport);
        return JsonResult.success(1);
    }

    /**
     * 将选中商品写入excel
     * @param ids 商品ID 逗号隔开
     * @return com.dzl.util.JsonResult<java.util.List   <   com.dzl.goods.pojo.vo.WelfareGoodsAttrVo>>
     * @date 2021/7/29 0029 15:57
     * @author wangjian
     */
    @PostMapping("/exportGoods")
    public JsonResult<List<WelfareSkuGoodsVo>> exportGoodsAttrVo(String ids, HttpServletResponse res) {
        List<WelfareSkuGoodsVo> goodsAttrVos = welfareGoodsAttrService.getGoodsAttrsByGoodsId(ids);
        welfareGoodsAttrService.export(goodsAttrVos, res);
        return JsonResult.success(goodsAttrVos);
    }
}
